import os

import yaml


class YamlUtil:
    def __init__(self):
        self.data_path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))),"data/")

    # 读yaml文件中的数据
    def read_extract_yaml(self):
        with open(self.data_path + 'extract.yaml', mode='r', encoding="utf-8") as f:
            value = yaml.safe_load(f)
            return value

    #读yaml文件中的数据
    def read_testcase_yaml(self, yaml_name,key_name=None):
        with open(self.data_path + yaml_name, mode='r', encoding= "utf-8") as f:
            value = yaml.safe_load(f)
            if key_name:
                return value[key_name]
        return value
    #将读出来的数据重新组装，组装成[{"request_info": 'request_info', "case_info": "case_info"},{"request_info": 'request_info', "case_info": "case_info"}.....]的样子，以满足在yaml中不重复写每个接口的request_info内容
    def extract_case(self, yaml_name,key_name):
        a = self.read_testcase_yaml(yaml_name, key_name)
        case_value = a[0]
        new_case = []
        for value in case_value['case_info']:
            new_case.append({"request_info": case_value['request_info'], "case_info": value})
        return new_case

    def write_extra_yaml(self, data):
        #1、with open(file) as f 当模式是写入时如果file不存在则在你写的路径上自动建这个file
        #写的方式有两个选择：mode ='w'每一次写都先清空文件内的所有内容再往里面写内容；mode ='a' 不会先清空，每次写都是追加在后面
        with open(self.data_path + 'extract.yaml', mode='a', encoding= "utf-8") as f:
            # 读取之前的yaml内容
            old_value = self.read_extract_yaml()
            if old_value:
                #和新传入的数据做结合
                for key,value in data.items():
                    old_value[key] = value #相同key的值就被替换掉了，而old_value原本没有的key则通过old_value[key] = value新增进old_value
                    self.clear_extract_yaml()#清除extract.yaml中的内容
                yaml.dump(data=old_value, stream=f, allow_unicode=True, sort_keys=False)#data：写入的数据, stream：文件, allow_unicode=True：遵循unicode编码, sort_keys=False：不设置的话默认为Ture指依据26个字母来给内容排序，False的话就会按照追加的顺序进行排序
            else:
                yaml.dump(data=data, stream=f, allow_unicode=True, sort_keys=False)

    def clear_extract_yaml(self):
        """清理extract.yaml"""
        with open(self.data_path + 'extract.yaml', mode='w', encoding= "utf-8") as f:
            f.truncate()


if __name__ == '__main__':
    #data = YamlUtil().extract_case('user_center.yaml', 'user_login_new')
    #print(data)
    data = {"code":201, "data":{"id1":3385, "address": "四川省顺风"}}
    YamlUtil().write_extra_yaml(data)
    #YamlUtil().read_extract_yaml()